package com.jn.rxjava.views;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jn.rxjava.R;
import com.jn.rxjava.adapter.ItemAdapter;
import com.jn.rxjava.entity.Item;
import com.jn.rxjava.service.ApiService;
import com.jn.rxjava.service.ResponseData;

import java.util.List;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.observers.DisposableObserver;
import io.reactivex.rxjava3.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ListActivity extends AppCompatActivity {
    private RecyclerView recyclerView;
    private ItemAdapter itemAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);

        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        // 获取传递的 URL
        String apiUrl = getIntent().getStringExtra("url");

        // 初始化 Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.oioweb.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create()) // 添加 RxJava 3 适配器
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        apiService.getItems() // 调用获取数据的方法
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DisposableObserver<ResponseData>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        // 可以在这里显示加载框
                    }

                    @Override
                    public void onNext(ResponseData response) {
                        List<Item> items = response.getResult();
                        itemAdapter = new ItemAdapter(ListActivity.this, items);
                        recyclerView.setAdapter(itemAdapter);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("ListActivity", "Error fetching items", e);
                        Toast.makeText(ListActivity.this, "获取数据失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onComplete() {
                        // 请求完成
                    }
                });
    }
}
